package libs
import (
	"fmt"
	"net"
)

type Server struct {
	Host string
	Port int
	Conn *net.TCPListener
	Handler   func(*Task)
	Num int32
	Tp *ThreadPool
	Ch chan Task
}

func NewServer(host string, port int,num int32,do func(*Task))(*Server,error){
	return &Server{
		Host:host,
		Port:port,
		Handler:do,
		Num:num,
	},nil
}

func (s *Server)Start() error{
	service := fmt.Sprintf("%s:%d",s.Host,s.Port)
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	if err !=nil{
		return  err
	}
	s.Conn, err = net.ListenTCP("tcp", tcpAddr)
	if err !=nil{
		return  err
	}
	s.Ch = make(chan Task)
	s.Tp = NewThreadPool(s.Num, s.Ch, s.Handler)
	s.Tp.Start()
	for {
		conn, err := s.Conn.Accept()
		if err != nil {
			continue
		}
		s.Ch <- Task{Client:conn}
	}
}